<?php

namespace app\admin\model;

use think\Exception;
use think\Model;
use think\model\relation\BelongsTo;


class Question extends Model
{
    // 表名
    protected $name = 'course_question';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'a_time_text',
        'u_time_text'
    ];

    /**
     * allSelect
     * @var string[]
     */
    public $allSelect = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'];

    public function course(): BelongsTo
    {
        return $this->belongsTo('app\admin\model\Course', 'course_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function getATimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['a_time']) ? $data['a_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['u_time']) ? $data['u_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setATimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    /**
     * buildHash
     * @param $question
     * @return string
     */
    public function buildHash($question): string
    {
        $text = $question['questionAsk'];
        foreach ($this->allSelect as $select) {
            if (!empty($question['answerOption'][$select])) {
                $text .= $question['answerOption'][$select];
            }
        }
        if (!empty($question['correctOption'])) {
            $text .= $question['correctOption'];
        }
        return md5($text);
    }

}
